package com.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.common.Result;
import com.demo.pojo.dto.AdminListDTO;
import com.demo.pojo.entity.Admin;
import com.demo.service.AdminService;
import org.springframework.http.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    
    @Autowired
    private AdminService adminService;
    
    /**
     * 分页查询管理员列表
     * @param pageNum 当前页
     * @param pageSize 每页大小
     * @param adminNo 管理员账号（可选）
     * @param adminName 管理员姓名（可选）
     * @param adminRole 角色（可选）
     * @param adminStatus 状态（可选）
     * @return 分页结果
     */
    @GetMapping("/listPage")
    public Result<IPage<AdminListDTO>> getAdminList(
            @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "adminNo", required = false) String adminNo,
            @RequestParam(name = "adminName", required = false) String adminName,
            @RequestParam(name = "adminRole", required = false) String adminRole,
            @RequestParam(name = "adminStatus", required = false) Integer adminStatus) {
        
        Page<Admin> page = new Page<>(pageNum, pageSize);
        IPage<AdminListDTO> result = adminService.getAdminList(page, adminNo, adminName, adminRole, adminStatus);
        
        return Result.success(result);
    }
    
    /**
     * 根据ID查询管理员
     * @param id 管理员ID
     * @return 管理员信息
     */
    @GetMapping("/select")
    public Result<Admin> getAdminById(@RequestParam Long id) {
        Admin admin = adminService.getAdminById(id);
        if (admin == null) {
            return Result.error("管理员不存在");
        }
        return Result.success(admin);
    }
    
    /**
     * 根据管理员账号查询
     * @param adminNo 管理员账号
     * @return 管理员信息
     */
    @GetMapping("/no/{adminNo}")
    public Result<Admin> getAdminByNo(@PathVariable String adminNo) {
        Admin admin = adminService.getAdminByNo(adminNo);
        if (admin == null) {
            return Result.error("管理员不存在");
        }
        return Result.success(admin);
    }
    
    /**
     * 管理员登录
     * @param body 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> body) {
        // 支持多种可能的字段名
        String adminNo = body.get("adminNo");
        if (adminNo == null) {
            adminNo = body.get("username");
        }
        if (adminNo == null) {
            adminNo = body.get("account");
        }
        
        String password = body.get("password");
        if (password == null) {
            password = body.get("pwd");
        }
        if (password == null) {
            password = body.get("adminPassword");
        }
        
        // 添加调试信息
        System.out.println("接收到的登录参数: " + body);
        System.out.println("解析后的账号: " + adminNo);
        System.out.println("解析后的密码: " + password);
        
        Admin admin = adminService.login(adminNo, password);
        Map<String, Object> resp = new HashMap<>();
        resp.put("user", admin);
        return Result.success(resp);
    }
    
    /**
     * 添加管理员
     * @param admin 管理员信息
     * @return 操作结果
     */
    @PostMapping(value = "/save", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<String> addAdmin(@RequestBody Admin admin) {
        try {
            boolean success = adminService.addAdmin(admin);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 添加管理员（表单提交：application/x-www-form-urlencoded）
     */
    @PostMapping(value = "/save", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Result<String> addAdminForm(Admin admin) {
        try {
            boolean success = adminService.addAdmin(admin);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 添加管理员（表单提交：multipart/form-data）
     */
    @PostMapping(value = "/save", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> addAdminMultipart(@ModelAttribute Admin admin) {
        try {
            boolean success = adminService.addAdmin(admin);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新管理员信息
     * @param admin 管理员信息
     * @return 操作结果
     */
    @PutMapping("/update")
    public Result<String> updateAdmin(@RequestBody Admin admin) {
        try {
            boolean success = adminService.updateAdmin(admin);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除管理员（通过ID）
     * @param id 管理员ID
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public Result<String> deleteAdmin(@RequestParam Long id) {
        boolean success = adminService.deleteAdmin(id);
        if (success) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }
    
    /**
     * 删除管理员（通过账号）
     * @param adminNo 管理员账号
     * @return 操作结果
     */
    @DeleteMapping("/deleteByNo")
    public Result<String> deleteAdminByNo(@RequestParam String adminNo) {
        try {
            boolean success = adminService.deleteAdminByNo(adminNo);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 批量删除管理员
     * @param ids 管理员ID列表
     * @return 操作结果
     */
    @DeleteMapping("/batch")
    public Result<String> deleteAdmins(@RequestBody List<Long> ids) {
        boolean success = adminService.deleteAdmins(ids);
        if (success) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    } 
}
